/***************************************************
1.权限分为 Operator Supervisor admin（权限级别由低到高）
2.每种权限的人只能设置比他级别低的人的权限
******************************************************/

#include "logindialog.h"
#include "ui_logindialog.h"
#include <QMessageBox>
#include <QDebug>
#include "database/databasequery.h"
#include "dataview/usermodel.h"
#include "common/common.h"
#include "common/gui/mymessagedialog.h"
//#include "useritemdelegate.h"
#include "database/dbtabuser.h"
#ifdef __CRAB_SCALE__
#include "communication/tcpclient.h"
#include "mainwidget_crab.h"
#endif
#include "mainwidget.h"

LoginDialog::LoginDialog(const QModelIndex& index,QWidget *parent) :
    TDialog(parent),
    ui(new Ui::LoginDialog)
{
    ui->setupUi(this);
    initUser(index);
    //setWindowFlags(Qt::Dialog);
    connect(ui->loginBtn,SIGNAL(clicked()),this,SLOT(Login()));
   // connect(ui->cancelBtn,SIGNAL(clicked()),this,SLOT(clear()));
    //connect(ui->passwd,SIGNAL())

    ui->cb_user->setFocus();
    ui->cb_user->setEditable(false);
#ifdef __CRAB_SCALE__
    ui->cb_user->setEditable(true);
    ui->cb_user->clear();

    connect(TcpClient::getInstance(),SIGNAL(loginOk()),this,SLOT(onLoginOk()));
    connect(TcpClient::getInstance(),SIGNAL(errorMsg(QString)),this,SLOT(onLoginFail(QString)));
#endif
    setModal(false);
    this->setFixedSize(SCREEN_WIDTH*5/12,SCREEN_HIGH*5/12); //20,800/3 = 532/4 =1
    this->move((SCREEN_WIDTH-width())/2,(SCREEN_HIGH-height())/12);

    //ui->comboBox->setFocusPolicy(Qt::NoFocus    );
}

/*
void LoginDialog::textChanged(const QString &str)
{
    if(str.length()==0)
    {
        QFont f("DejaVu Sans",4);
        ui->comboBox->setEditText("Enter User Name");
        //ui->comboBox->setCursor(0);
        ui->comboBox->setFont(f);
    }
    else
    {

        QFont f("DejaVu Sans",6);
        ui->comboBox->setFont(f);
    }
}*/

void LoginDialog::clear()
{
    if(ui->passwd->hasFocus())
    {
        ui->passwd->clear();
    }
    else if(ui->cb_user->hasFocus())
    {
        //ui->comboBox->clear();
        //ui->comboBox->setCurrentIndex(1);
    }
}

void LoginDialog::keyPressEvent(QKeyEvent *e)
{
//#ifdef __CRAB_SCALE__
//    if(e->key()==KEY_MENU){
//        GetMainWidget()->openSetting();
//        e->accept();
//        return;
//    }
//#endif
        e->ignore();
}


QString LoginDialog::technicianString()
{
    return tr("技术员");
}

void LoginDialog::initUser(const QModelIndex& index)
{
    DataBaseQuery query;
    QComboBox *cb =  ui->cb_user;//ui->comboBox;
    QStringList str;
    str<<DBTabUser::_PERMISSION
        <<DBTabUser::_USER_NAME;
    query.selectTable(DBTabUser::TAB_NAME,&str);

    int name = query.record().indexOf(DBTabUser::_USER_NAME);

    cb->addItem(technicianString(),0);
    int i=0; ///
    while(query.next())
    {
        i++;
        //int custom_id = query.value(id).toInt();
        QString user_name =  query.value(name).toString();
//        qDebug()<<"sxxxxxxxxxxxxxxxx"<<query.value(hide)<<query.value(hide).toBool();
        //hideMap.insert(i,query.value(hide).toBool());

        cb->addItem(user_name);
    }
    if(index!=QModelIndex())
    {
        QString name = index.data(UserModel::ROLE_NAME).toString();
        int idx = cb->findText(name);
        cb->setCurrentIndex(idx);
    }
    else
        cb->setCurrentIndex(0);
}

LoginDialog::~LoginDialog()
{
    delete ui;
}

int LoginDialog::mPermission = UserModel::TECH;
QString LoginDialog::mUser = LoginDialog::technicianString();

int LoginDialog::permission()
{
    return mPermission;
}

void LoginDialog::setPermission(int permission)
{
    mPermission = permission;
}




QString LoginDialog::user()
{
    return mUser;
}


bool LoginDialog::changeUserByUserCode(const QString& user_code)
{

}

void LoginDialog::setUserName(QModelIndex index)
{
    ui->cb_user->setCurrentIndex(index.row()+1);
}



//void LoginDialog::close()
//{
//    permission = UserModel::GUEST;
//    StatusBar::getStatusBar()->changeOperator("Guest");
//    reject();
//}
#define SUPPER_PASSWD "lb&3614"
#define DEFAULT_PASSWD "000000"
void LoginDialog::Login()
{
//    qDebug()<<"sxxxxxxxxxxxxxxxx"<<hideMap;

    QComboBox *cb = ui->cb_user;
   // int user_code = cb->itemData(cb->currentIndex()).toInt();
    QString user = cb->currentText();
    QString passwd = ui->passwd->text();
#ifdef __CRAB_SCALE__/*
    if(1)
    {
        emit hasLogin();
        accept();
        return;
    }
    else
    {
        goto PASSWD_WRONG;
    }*/
  //QTimer *timer = new QTimer(this);
    //connect(time,SIGNAL(time))
    TcpClient::getInstance()->login(user,passwd);


    //connect(TcpClient::getInstance())
    return ;
#else
    if(QString::compare(user,technicianString(),Qt::CaseInsensitive)==0)
    {
        if((QString::compare(passwd,DEFAULT_PASSWD)==0) ||
            (QString::compare(passwd,SUPPER_PASSWD)==0 ))
        {
            mPermission = UserModel::TECH;
            mUser = cb->currentText();
            //StatusBar::getStatusBar()->changeOperator(mUser);
           GetMainWidget()->changeUser(mUser);
            emit hasLogin();
            accept();
        }
        else
        {
            goto PASSWD_WRONG;
        }
    }
    else
    {


        int ret = UserModel::checkPasswd(user,passwd);
        if(ret>=0)
        {
            mPermission = ret;
            mUser = user;
            //StatusBar::getStatusBar()->changeOperator(mUser);
            GetMainWidget()->changeUser(mUser);
            emit hasLogin();
            accept();

        }
        else
        {
            goto PASSWD_WRONG;
        }

    }
    return;
#endif
PASSWD_WRONG:
    ui->passwd->clear();
    //MyMessageDialog::warning(0,"Login error","User name or password is wrong!");
    MyMessageDialog::warning(0,"登录失败","用户名或密码错误!");

}
#ifdef __CRAB_SCALE__
void LoginDialog::onLoginOk()
{
    TcpClient::getInstance()->disconnectFromHost();

    mPermission = UserModel::PERMISION_TECH;
    mUser = ui->cb_user->currentText();
    StatusBar::getStatusBar()->changeOperator(mUser);
    emit hasLogin();

    accept();
}

//void LoginDialog::onLoginTimeOut()
//{
//     TcpClient::getInstance()->disconnectFromHost();
//     MyMessageDialog::warning(0,"Login error","登录超时");

//     mTimer->stop();
//}

void LoginDialog::onLoginFail(const QString &str)
{
    TcpClient::getInstance()->disconnectFromHost();
    MyMessageDialog::warning(0,"Login error",str);
}
#endif
